package com.yjf.ljr.activity;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.widget.LinearLayout;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.UpdateInfoDataClass;
import com.yjf.ljr.dataclass.UpdateInfoDataClass.UpdateInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.SPreferences;

/**
 * 闪屏页
 */
public class SplashActivity extends IjActivity {

	public static final String TAG = SplashActivity.class.getName();
	public static String mMachineKey = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setVerify(false);

		setContentView(R.layout.activity_splashpage);
		mMachineKey = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		// showWelcomeImg();
		new CheckUpdateTask().execute();
	}

	@SuppressWarnings("deprecation")
	private void showWelcomeImg() {
		String time = SPreferences.getWelComeImgTime(this);
		if (TextUtils.isEmpty(time)) {
			return;
		}
		String[] ss = time.split("&");
		String startTime = ss[0];
		String endTime = ss[1];
		if (startTime != null && endTime != null) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.main_view);
			long currTime = new Date().getTime();
			if (convertStrToDate(startTime).getTime() <= currTime && currTime <= convertStrToDate(endTime).getTime()
					&& existImg()) {
				layout.setBackgroundDrawable(Drawable.createFromPath(CommonData.IMAMGE_DIR_SD + "/splash1.jpg"));
			}
		}
	}

	private Date convertStrToDate(String str) {
		if (TextUtils.isEmpty(str)) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	private boolean existImg() {
		File f = new File(CommonData.IMAMGE_DIR_SD + "/splash1.jpg");
		return f.exists();
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CommonData.SUCCESS:
				Intent intent = new Intent();
				// if (!SPreferences.isFirst(mContext)) {
				// intent.setClass(SplashActivity.this, GroupActivity.class);
				// } else {
				// intent.setClass(SplashActivity.this, WelcomeActivity.class);
				// }
				intent.setClass(SplashActivity.this, GroupActivity.class);
				startActivity(intent);
				finish();
				break;
			}
		}
	};

	/** 检查升级 **/
	class CheckUpdateTask extends AsyncTask<Void, Void, String> {
		private UpdateInfoDataClass dc = new UpdateInfoDataClass();

		@Override
		protected String doInBackground(Void... params) {
			RequestObject reqObj = new RequestObject();
			reqObj.method = "appUpdateInfo";
			reqObj.map.put("verCode", "" + AppUtil.getVersionCode(SplashActivity.this));
			reqObj.map.put("verName", AppUtil.getVersionName(SplashActivity.this));
			reqObj.map.put("channelCode", AppUtil.getChanel(SplashActivity.this));
			reqObj.map.put("type", "ANDROID");
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
				pause();
			} else {
				if (dc.updateMessage != null) {
					final UpdateInfo info = dc.updateMessage;
					if ((AppUtil.getVersionCode(SplashActivity.this) < info.forceUpdateCode)) {// 强制更新
						new AlertDialog.Builder(SplashActivity.this).setTitle(R.string.newVersion)
								.setMessage(info.updateInfo)
								.setPositiveButton(R.string.btn_thisTime, new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Intent intent = new Intent(SplashActivity.this, UpdateSoftActivity.class);
										intent.putExtra("updateUrl", info.updateUrl);
										startActivity(intent);
										SplashActivity.this.finish();
									}
								}).setOnCancelListener(new OnCancelListener() {
									@Override
									public void onCancel(DialogInterface dialog) {
										SplashActivity.this.finish();
									}
								}).show();
					} else if ((AppUtil.getVersionCode(SplashActivity.this) < info.optionalUpdateCode)) {// 可选更新
						// 让用户选择是否更新
						new AlertDialog.Builder(SplashActivity.this).setTitle(R.string.newVersion)
								.setMessage(info.updateInfo)
								.setPositiveButton(R.string.btn_thisTime, new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Intent intent = new Intent(SplashActivity.this, UpdateSoftActivity.class);
										intent.putExtra("updateUrl", info.updateUrl);
										startActivity(intent);
										SplashActivity.this.finish();
									}
								}).setNegativeButton(R.string.btn_nextTime, new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Intent intent = new Intent();
										// if (SPreferences.isFirst(mContext)) {
										// intent.setClass(SplashActivity.this,
										// WelcomeActivity.class);
										// } else {
										// intent.setClass(SplashActivity.this,
										// GroupActivity.class);
										// }
										intent.setClass(SplashActivity.this, GroupActivity.class);
										startActivity(intent);
										SplashActivity.this.finish();
									}
								}).setCancelable(false).show();
					} else {// 不用更新,直接进入应用
						pause();
					}
				} else {
					pause();
				}
			}
			dismissProgressDialog();
		}
	}

	private void pause() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
					mHandler.sendEmptyMessage(CommonData.SUCCESS);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public boolean onFling(android.view.MotionEvent e1, android.view.MotionEvent e2, float velocityX, float velocityY) {
		return false;
	};
}
